<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\ApprovalList;
use App\Models\ApprovalSet;
use App\Models\ApprovalLog;
use App\Models\user;
use App\Models\Grid;
use App\Http\Controllers\Controller;

class AuthApi extends Controller
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (!auth('api')->check()) {
            return showError('用户未登录',5000);
        }
        if (auth('api')->user()->status==0) {
            return showError('用户已被禁用',1000);
        }
        
        // 触发审批-业务功能(修改数据)
        $apply_type=$request->input('apply_type','');
        if($apply_type){
           
            $user=auth('api')->user()??'';
            $params=$request->all();

            if(isset($params['grid_id'])){
                $grid=Grid::query()->select('project_id','street_id','village_id')->where('id',$params['grid_id'])->first();
            }else{
                $user['village_id']=explode(',',$user['village_id'])[0];
                $grid= $user;
            }

            // 和BasicApi区别

            // 触发面积表并开始审批后，入户测绘不能修改
            if(in_array($apply_type,[1,2,3,4,5,6])){
                $apply_table=ApprovalList::query()
                ->where('grid_id',$params['grid_id']??0)
                ->where('apply_status','<>',0)
                ->whereIn('apply_type',[14,15,16,17,18])
                ->value('id');
               if($apply_table){
                    return showError('已提交面积表审批,无法修改');
               }
            }
           
            // 有完成审批的，完成审批通过后，修改审批不能再次发起(签约及签约后 测绘 评估 户口 土地证)
            $apply_status=[9=>19,10=>20,11=>21,12=>22,13=>23,6=>26,7=>27,3=>24,4=>25];
            if(isset($apply_status[$apply_type])){
                $sign_end_edit=ApprovalList::query()
                ->where('grid_id',$params['grid_id']??0)
                ->where('apply_type',$apply_status[$apply_type])
                ->where('apply_status',1)
                ->value('id');
                if($sign_end_edit){
                        return showError('当前操作审批已通过，无法修改');
                }
            }
           
            //存在相同未开始审批，直接修改申请内容，不再次发起审批
            $find_list=ApprovalList::query()
            ->select('id','apply_status')
            ->where('apply_type',$apply_type)
            ->where('user_id',$user->id??0)
            ->where('grid_id',$params['grid_id']??0)
            ->orderByDesc('id')
            ->first();
            if($find_list){
                if($find_list['apply_status']==0){
                    $update=ApprovalList::query()->where('id',$find_list['id'])->update(['content'=>json_encode($params)]);
                    return showSuccess('添加审批成功！');   
                }
    
                if($find_list['apply_status']==3){
                    return showError('存在当前类型未完成审批，暂时无法再次申请');
                }
            }

            $approval_set=ApprovalSet::query()
                ->where('project_id',$grid->project_id??2)
                ->where('street_id',$grid->street_id??3)
                ->where('village_id',$grid->village_id??1)
                ->where('template_id',$apply_type)
                ->where('status',1)
                ->first();
            if($approval_set){
                $data['user_id']=$user->id??0;
                $data['project_id']=$grid->project_id??0;
                $data['apply_type']=$apply_type;
                unset($params['apply_type']);
                $data['apply_reason']=$params['apply_reason']??'';
                unset($params['apply_reason']);
                $data['content']=json_encode($params);
                $data['grid_id']= $params['grid_id']??0;
                $data['set_id']= $approval_set['id'];
                $res=ApprovalList::query()->create($data);
    
                $content=json_decode($approval_set['content'],true);
                foreach($content as $k=> $v){
                    $user_arr=explode(',',$v['user_ids']);
                    foreach($user_arr as $vv){
                        $logData['list_id']=$res->id;
                        $logData['apply_user_id']=$vv;
                        $logData['step']=$k+1;
                        $approval_set=ApprovalLog::query()
                                ->create($logData);
                    }
                }
               
                return showSuccess('添加审批成功！');
            }   
        }

        //触发审批-拒绝表审批后在审批详情修改后提交
        $table_type=$request->input('table_type','');
        if($table_type){
            $params=$request->all();

            if(!$this->findApproval($params['grid_id']??0, $table_type)){
                $this->setApproval($params['grid_id']??0,$table_type);
            }
        }

        return $next($request);
    }
}